package com.lie.usercenter.aop.aspect;

import com.lie.usercenter.annotation.SysLog;
import com.lie.usercenter.aop.domain.SysLogDO;
import com.lie.usercenter.aop.service.SysLogService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.util.StopWatch;
import org.springframework.web.context.request.RequestAttributes;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.lang.reflect.Method;

/**
 * 系统日志切面
 * @author MTF
 * @date 20221122
 */
@Aspect
@Component
public class SysLogAspect {

    @Resource
    private SysLogService sysLogService;

    @Pointcut("@annotation(com.lie.usercenter.annotation.SysLog)")
    public void logPointCut(){

    }

    @Around("logPointCut()")
    private Object savaLog(ProceedingJoinPoint point) throws Throwable {
        // 计时
        StopWatch stopWatch = new StopWatch();
        stopWatch.start();
        // 执行原方法
        Object result = point.proceed();
        stopWatch.stop();
        long totalTimeMillis = stopWatch.getTotalTimeMillis();
        // 获取请求路径
        RequestAttributes requestAttributes = RequestContextHolder.currentRequestAttributes();
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) requestAttributes).getRequest();
        String url = httpServletRequest.getRequestURI();
        // 请求类名
        String className = point.getTarget().getClass().getName();
        // 请求方法名
        MethodSignature signature = (MethodSignature) point.getSignature();
        String methodName = signature.getName();
        // 请求参数
        Object[] args = point.getArgs();

        SysLogDO sysLogDO = new SysLogDO();
        sysLogDO.setUrl(url);
        sysLogDO.setClassName(className);
        sysLogDO.setMothodName(methodName);
        sysLogDO.setParams(args);
        sysLogDO.setRunningTime(totalTimeMillis);
        // 获取注解描述
        Method method = signature.getMethod();
        SysLog sysLog = method.getAnnotation(SysLog.class);
        if (sysLog != null){
            sysLogDO.setRemark(sysLog.value());
        }
        sysLogService.sava(sysLogDO);
        return result;
    }

}
